#include "stdafx.h"
#include "caProcCtrl.h"

caCProcCtrl::caCProcCtrl(caIProcDiplomat *pa)
{
	m_attack= pa;
	m_alloc = NULL;
	m_rwctrl= NULL;
	m_sender= NULL;
}

caCProcCtrl::~caCProcCtrl()
{
	if(m_attack)
	{
		m_attack->DestorySender();
		m_attack->DestoryRwCtrl();
		m_attack->DestoryAlloc();
		m_attack->DetachProc();
		delete m_sender;
		delete m_alloc;
		delete m_rwctrl;
		delete m_attack;
	}
}

BOOL caCProcCtrl::Attach(DWORD pid)
{
	if(m_attack)
	{
		if(m_attack->AttachProc(pid))
		{
			if((m_alloc=m_attack->CreateAlloc())!=NULL)
			{
				if((m_rwctrl=m_attack->CreateRwCtrl())!=NULL)
				{
					if((m_sender=m_attack->CreateSender())!=NULL)
					{
						return TRUE;
					}
					else
					{
						m_attack->DestoryRwCtrl();
						m_attack->DestoryAlloc();
						m_attack->DetachProc();
						delete m_rwctrl;
						delete m_alloc;
						m_alloc = NULL;
						m_rwctrl= NULL;
					}
				}
				else
				{
					m_attack->DestoryAlloc();
					m_attack->DetachProc();
					delete m_alloc;
					m_alloc=NULL;
				}
			}
			else
			{
				m_attack->DetachProc();
			}
		}
	}
	return FALSE;
}

BOOL caCProcCtrl::Detach()
{
	if(m_attack)
	{
		if(m_sender)
		{
			m_attack->DestorySender();
			delete m_sender;
		}
		if(m_rwctrl)
		{
			m_attack->DestoryRwCtrl();
			delete m_rwctrl;
		}
		if(m_alloc)
		{
			m_attack->DestoryAlloc();
			delete m_alloc;
		}		
		m_alloc =NULL;
		m_rwctrl=NULL;
		m_sender=NULL;
	}
	return FALSE;
}

caIRMemAllocater* caCProcCtrl::GetRMemAllocater()
{
	return m_alloc;
}

caIRMemReadWrite* caCProcCtrl::GetRMemReadWrite()
{
	return m_rwctrl;
}

IMessageSend* caCProcCtrl::GetMessageSend()
{
	return m_sender;
}

PVOID caCProcCtrl::GetMemory(size_t size)
{
	if(m_alloc)
		return m_alloc->GetMemory(size);
	else
		return NULL;
}

void caCProcCtrl::FreeMemory(PVOID raddr)
{
	if(m_alloc)
		m_alloc->FreeMemory(raddr);
}

DWORD caCProcCtrl::Read(PVOID raddr,PVOID buffer, size_t size)
{
	if(m_rwctrl)
		return m_rwctrl->Read(raddr,buffer,size);
	else
		return 0;
}

DWORD caCProcCtrl::Write(PVOID raddr, PVOID buffer, size_t size)
{
	if(m_rwctrl)
		return m_rwctrl->Write(raddr,buffer,size);
	else
		return 0;
}

LONGLONG caCProcCtrl::SendMessage(IMessage* message)
{
	if(m_sender)
		return m_sender->Send(message);
	else
		return 0;
}